<template>
  <div id="listUserView">
    <!--搜索用户-->
    <a-form :model="searchParams" layout="inline" class="searchUserForm">
      <a-form-item field="title" label="用户编号" tooltip="精确匹配">
        <a-input
          v-model="searchParams.id"
          placeholder="请输入用户id"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="userAccount" label="账号" tooltip="精确匹配">
        <a-input
          v-model="searchParams.userAccount"
          placeholder="请输入用户账号"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="userRole" label="用户角色">
        <a-select
          :style="{ width: '180px' }"
          v-model="searchParams.userRole"
          placeholder="请选择用户角色"
          allow-clear
        >
          <a-option value="user">普通用户</a-option>
          <a-option value="admin">管理员</a-option>
          <a-option value="ban">封号</a-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button
          type="outline"
          shape="round"
          status="normal"
          @click="doSearch"
        >
          搜索
        </a-button>
      </a-form-item>
    </a-form>
    <!--题目表格-->
    <a-table
      :columns="columns"
      :data="data"
      :pagination="pagination"
      @page-change="onPageChange"
      column-resizable
      filter-icon-align-left
    >
      <!--用户头像-->
      <template #userAvatar="{ record }">
        <a-avatar v-if="record.userAvatar">
          <img :src="record.userAvatar" alt="" />
        </a-avatar>
        <a-avatar v-else>
          <IconUser />
        </a-avatar>
      </template>

      <!--用户角色-->
      <template #userRole="{ record }">
        <a-tag v-if="record.userRole == 'user'" color="green">普通用户</a-tag>
        <a-tag v-else-if="record.userRole == 'admin'" color="blue"
          >管理员
        </a-tag>
        <a-tag v-else color="#f53f3f">封号</a-tag>
      </template>

      <!--创建时间-->
      <template #createTime="{ record }">
        {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>

      <!--更新时间-->
      <template #updateTime="{ record }">
        {{ dayjs(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>

      <!--操作列-->
      <template #optional="{ record }">
        <a-button type="primary" shape="round" @click="getUserInfo(record)">
          修改
        </a-button>
      </template>
    </a-table>

    <!--用户信息对话框-->
    <a-modal
      v-model:visible="userInfoModelVisible"
      title="修改用户信息"
      @cancel="handleCancel"
      @ok="handleOk"
      unmountOnClose
    >
      <a-form :model="userInfo" label-align="left">
        <!--用户头像-->
        <a-spin
          :loading="uploadLoading"
          tip="上传中..."
          style="margin: 0 auto 15px"
        >
          <a-upload
            action="/"
            :fileList="file ? [file] : []"
            :show-file-list="false"
            @change="onChange"
            :custom-request="uploadAvatar"
          >
            <template #upload-button>
              <div
                class="arco-upload-list-picture custom-upload-avatar"
                v-if="userInfo && userInfo.userAvatar"
              >
                <img :src="userInfo?.userAvatar" alt="" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
              </div>
              <div class="arco-upload-picture-card" v-else>
                <div class="arco-upload-picture-card-text">
                  <IconPlus />
                  <div style="margin-top: 10px; font-weight: 600">Upload</div>
                </div>
              </div>
            </template>
          </a-upload>
        </a-spin>
        <!--用户编号-->
        <a-form-item field="id" label="用户编号">
          <a-input v-model="userInfo.id" disabled />
        </a-form-item>
        <!--用户账号-->
        <a-form-item field="userAccount" label="用户账号">
          <a-input v-model="userInfo.userAccount" disabled />
        </a-form-item>
        <!--用户昵称-->
        <a-form-item field="userName" label="用户昵称">
          <a-input v-model="userInfo.userName" />
        </a-form-item>
        <!--用户角色-->
        <a-form-item field="userRole" label="用户角色">
          <a-select v-model="userInfo.userRole">
            <a-option value="user">普通用户</a-option>
            <a-option value="admin">管理员</a-option>
            <a-option value="ban">封号</a-option>
          </a-select>
        </a-form-item>
        <!--用户介绍-->
        <a-form-item field="userProfile" label="用户介绍">
          <a-textarea
            v-model="userInfo.userProfile"
            placeholder="请输入用户介绍"
            :max-length="50"
            allow-clear
            show-word-limit
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from "vue";
import { UserControllerService } from "../../../generated";
import { FileItem, Message } from "@arco-design/web-vue";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import { useRouter } from "vue-router";
import axios from "axios";
import { baseUrl } from "@/plugins/axios";

const router = useRouter();

// 表格列
const columns = [
  {
    dataIndex: "id",
    title: "用户编号",
    align: "center",
  },
  {
    dataIndex: "userAccount",
    title: "账号",
    align: "center",
  },
  {
    dataIndex: "userName",
    title: "昵称",
    align: "center",
    ellipsis: true,
  },
  {
    slotName: "userAvatar",
    title: "头像",
    align: "center",
  },
  {
    slotName: "userRole",
    title: "角色",
    align: "center",
  },
  {
    slotName: "createTime",
    width: 125,
    tooltip: true,
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
    title: "创建时间",
    align: "center",
    ellipsis: true,
  },
  {
    slotName: "updateTime",
    width: 125,
    tooltip: true,
    sortable: {
      sortDirections: ["ascend", "descend"],
    },
    title: "更新时间",
    align: "center",
    ellipsis: true,
  },
  {
    slotName: "optional",
    title: "操作",
    align: "center",
  },
];

// 用户信息对话框的显隐
const userInfoModelVisible = ref(false);

// 上传头像文件
const file = ref();

// 用户信息表单数据
const userInfo = ref();

/**
 * 点击用户信息对话框取消时触发
 */
const handleCancel = () => {
  userInfoModelVisible.value = false;
};

/**
 * 点击用户信息对话框的确定触发
 */
const handleOk = async () => {
  const res = await UserControllerService.updateUserUsingPost(userInfo.value);
  if (res.code === 0) {
    userInfoModelVisible.value = false;
    Message.success("用户信息更新成功");
  } else {
    Message.error("用户信息更新失败");
  }
};

/**
 * 点击修改按钮，获取用户信息
 * @param record 当前记录
 */
const getUserInfo = async (record: any) => {
  userInfo.value = record;
  userInfoModelVisible.value = true;
};

// 上传头像加载中状态标识
const uploadLoading = ref(false);

/**
 * 上传头像状态发生改变时触发
 * @param _
 * @param currentFile 当前文件
 */
const onChange = async (_: never, currentFile: FileItem) => {
  file.value = {
    ...currentFile,
  };
};

/**
 * 上传头像
 */
const uploadAvatar = async () => {
  // 上传状态标识
  uploadLoading.value = true;
  // 创建一个FormData对象，用于上传文件
  const formData = new FormData();
  formData.append("file", file.value.file); // 'file' 是文件字段的名称

  // 发送POST请求到后端接口
  await axios
    .post(baseUrl + "/api/file/upload", formData, {
      headers: {
        "Content-Type": "multipart/form-data", // 设置正确的Content-Type
      },
    })
    .then((res) => {
      // console.log("上传头像结果数据：" + JSON.stringify(res.data));
      if (res.data != null) {
        userInfo.value!.userAvatar = res.data.data;
        Message.success("上传头像成功，点击确定后生效");
      } else {
        Message.error("上传头像失败！" + JSON.stringify(res.data));
      }
    })
    .catch((error) => {
      Message.error("上传头像异常！" + error);
    });
  // 上传状态标识
  uploadLoading.value = false;
};

// 数据列表
const data = ref([]);

// 搜索表单
const searchParams = ref({
  current: 1,
  pageSize: 10,
  id: null,
  userAccount: null,
  userRole: null,
  sortField: "createTime",
  sortOrder: "descend",
});

// 分页结果参数
let pagination = reactive({
  showTotal: true,
  current: 0,
  pageSize: 0,
  total: 0,
});

/**
 * 加载数据
 */
const loadData = async () => {
  const res = await UserControllerService.listUserByPageUsingPost(
    searchParams.value as any
  );
  if (res.code === 0) {
    // 数据赋值
    data.value = res.data.records;
    // 分页结果参数赋值
    pagination.total = Number(res.data.total);
    pagination.current = Number(res.data.current);
    pagination.pageSize = Number(res.data.size);
  } else {
    Message.error("获取数据失败，" + res.message);
  }
};

/**
 * 搜索
 */
const doSearch = () => {
  // 这里需要重置页号，不然你在第二页搜索第一页的内容，会搜不到
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};

/**
 * 监听 () => { } 中的内容，
 * 内容中的变量（例如searchParams）发生改变时会再次触发() => { }中的内容（即loadData()重新加载数据）
 */
watchEffect(() => {
  loadData();
});

/**
 * 页码改变时触发
 * @param page 当前页码
 */
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};
</script>

<style scoped>
/*搜索用户表单*/
.searchUserForm {
  justify-content: center;
  align-content: center;
  margin-bottom: 20px;
}
</style>
